package xyz.bmj.spider;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.StreamProgress;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.bmj.model.BResourceResponse;
import xyz.bmj.model.MediaResponse;
import xyz.bmj.model.MlUrl;
import xyz.bmj.util.Constant;
import xyz.bmj.util.CoverTool;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class Spider {
    public List<BResourceResponse.DataBean.MediasBean> mediaList() {
        MlUrl mlUrl = new MlUrl();
        String url = mlUrl.toString();
        String r = HttpUtil.get(url);
        BResourceResponse brr = JSONUtil.toBean(r, BResourceResponse.class);
        return brr.getData().getMedias();
    }

    public List<BResourceResponse.DataBean.MediasBean> mediaListAllItem(MlUrl ml) {
        String url = ml.toString();
        String r = HttpUtil.get(url);
        BResourceResponse brr = JSONUtil.toBean(r, BResourceResponse.class);
        ml.setTotal(brr.getData().getInfo().getMedia_count());
        List<BResourceResponse.DataBean.MediasBean> res = brr.getData().getMedias();
        if (ml.hasNextPage()) {
            ml.getNextPageUrl();
            res.addAll(mediaListAllItem(ml));
        }
        return res;
    }


    public String audioUrl(String url) {
        String r = HttpUtil.get(url + "/");
        String pattern = "<script>window.__playinfo__=(.*?)</script>";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(r);
        if (m.find()) {
            r = m.group().replaceAll("<script>window.__playinfo__=", "").replaceAll("</script>", "");
            MediaResponse mr = JSONUtil.toBean(r, MediaResponse.class);
            List<MediaResponse.DataBean.DashBean.AudioBean> audios = mr.getData().getDash().getAudio();
            return audios.get(0).getBase_url();
        }
        return "";
    }

    public void downLoad(String title, String bv) {
        title = title.replaceAll("[/\\\\'\"|]", "_");
        String url = audioUrl(Constant.URL_BASE + bv);
        String fileNameM4a = (StrUtil.isNotBlank(Constant.OUT_FILE) ? Constant.OUT_FILE + File.separator + "b" : Constant.BASE_PATH + "audio") + File.separator + title + ".m4a";
        String fileNameMp3 = (StrUtil.isNotBlank(Constant.OUT_FILE) ? Constant.OUT_FILE + File.separator + "mp3" : Constant.BASE_PATH + "audio") + File.separator + title + ".mp3";
        log.info("即将下载文件{}", fileNameM4a);
        try {
            String finalTitle = title;
            long size = HttpRequest.get(url)
                    .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36")
                    .header(Header.REFERER, "https://www.bilibili.com")
                    .header(Header.ORIGIN, url)
                    .executeAsync()
                    .writeBody(FileUtil.file(fileNameM4a), new StreamProgress() {
                        @Override
                        public void start() {

                        }

                        @Override
                        public void progress(long l) {

                        }

                        @Override
                        public void finish() {
                            try {
                                CoverTool.m4aToWav(new File(fileNameM4a), new File(fileNameMp3));
                            } catch (Exception e) {
                                FileUtil.appendUtf8String(e.getLocalizedMessage() + "\n", FileUtil.newFile(Constant.BASE_PATH + "log" + File.separator + finalTitle + ".cover.err"));
                                e.printStackTrace();
                            }
                        }
                    });
            System.out.println("Download size: " + size);
        } catch (Exception e) {
            FileUtil.appendUtf8String(e.getLocalizedMessage() + "\n", FileUtil.newFile(Constant.BASE_PATH + "log" + File.separator + title + ".download.err"));
            log.error("错误title {}", title);
            e.printStackTrace();
        }

//        long size = HttpUtil.downloadFile(url, FileUtil.file(""));
//        System.out.println("Download size: " + size);
//        log.info("下载文件{}完成", fileNameM4a);
    }

    public static void main(String[] args) {

    }

}
